const path = require('path')
const { app, BrowserWindow, screen, protocol } = require('electron')

const createProtocol = require('./createProtocol')
const MenuBuilder = require('./MenuBuilder')
const setupDevtool = require('./setupDevtool')
const handleIPC = require('./handleIPC')
const { devToolVisible } = require('./config')

const isDev = process.env.NODE_ENV === 'development'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'lichengviteos', privileges: { secure: true, standard: true } }])

let mainWindow = null

app.allowRendererProcessReuse = true

// 按住devtool
if (devToolVisible) setupDevtool()

const createWindow = async () => {
  const size = screen.getPrimaryDisplay().size

  const winWidth = size.width * 0.65
  const winHeight = size.height * 0.8

  mainWindow = new BrowserWindow({
    height: winHeight,
    width: winWidth,
    minHeight: winHeight,
    minWidth: Math.max(winHeight, 1300),
    icon: path.resolve('icons/256x256.png'),
    show: false,
    webPreferences: {
      // nodeIntegration: true,
      webSecurity: false,
      preload: path.join(__dirname, '../preload/index.js'),
      enableRemoteModule: true, // 启动远程模块警告
    },
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow && mainWindow.show() // 初始化后再显示
  })

  if (isDev) {
    await mainWindow.loadURL('http://localhost:5999')
  } else {
    createProtocol('lichengviteos')
    mainWindow.loadURL('lichengviteos:///./index.html')
  }

  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined')
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize()
    } else {
      mainWindow.show()
      mainWindow.focus()
    }
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // 菜单设置
  new MenuBuilder(mainWindow).buildMenu()
}

/**
 * Add event listeners...
 */
app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('ready', () => {
  createWindow()
  handleIPC()
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
